package com.bubaiwantong.algorithms1.select;

/**
 * @author bubaiwantong
 * @date 2022/12/7 23:38
 * @description this is a class file created by bubaiwantong in 2022/12/7 23:38
 */
public class HeapSort {


    public static void main(String[] args) {
        int[] arr = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
        HeapSort sort = new HeapSort();
        sort.print(arr);
        sort.sort(arr);
        sort.print(arr);
    }


    /**
     * 大根堆排序
     *
     * @param arr
     */
    public void sort(int arr[]) {
        for (int i = arr.length / 2; i > 0; i--) {
            adjust(arr, i, arr.length);
        }

        for (int i = arr.length - 1; i > 0; i--) {
            adjust(arr, 0, i);
            swap(arr, 0, i);
        }

    }

    /**
     * 调整大根堆
     *
     * @param arr
     * @param i
     * @param length
     */
    public void adjust(int arr[], int i, int length) {
        int temp = arr[i];
        for (int k = 2 * i + 1; k < length; k = 2 * k + 1) {
            if (k + 1 < length && arr[k] < arr[k + 1]) {
                k += 1;
            }
            if (temp > arr[k]) {
                break;
            } else {
                arr[i] = arr[k];
                i = k;
            }
        }
        arr[i] = temp;
    }

    /**
     * 交换
     *
     * @param arr
     * @param i
     * @param j
     */
    public void swap(int arr[], int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    /**
     * 输出数组
     *
     * @param arr
     */
    public void print(int arr[]) {
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
    }


}
